package very.util.http

import org.json4s.{Formats, JValue}
import org.json4s.native.Serialization.write
import ws.very.util.json.JsonHelper

import scalaj.http.{HttpRequest, HttpResponse}

trait Http4SRequestWrapper extends JsonHelper {
  protected def getCCParams(cc: Product) = {
    val values = cc.productIterator
    cc.getClass.getDeclaredFields.map(_.getName -> values.next)
  }

  implicit class HttpRequestWrapper(request: HttpRequest) {
    def extract[T](implicit formats: Formats, mf: scala.reflect.Manifest[T]) = {
      jsonResult.map(_.extract[T])
    }
    // TODO: 危险方法， 不支持 case class 复杂数据结构
    def params[T <: Product](p: T) = {
      request.params(
        getCCParams(p)
          .map {
            case (key, None) => (key, "")
            case (key, Some(value)) => key -> value.toString
            case (key, value) =>
              (key, value.toString)
          }
          .filter(_._2 == "")
      )
    }

    def opResult: Boolean = {
      request.asString.is2xx
    }

    def putData[T <: AnyRef](data: T) = {
      request.put(write(data))
    }

    def stringResult: Either[HttpResponse[String], String] = {
      val resp = request.asString
      if (resp.is2xx) {
        resp.body
      } else {
        resp
      }
    }

    def jsonResult:Either[HttpResponse[String], JValue] = {
      val resp = request.asString
      if (resp.is2xx) {
        parseJson(resp.body)
      } else {
        resp
      }
    }
  }

}
